using XmWinKit.Common;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace XmWinKit.Components
{
    public enum XmButtonType
    {
        Plain,
        Fill,
        Text
    }

    public enum XmButtonShowMode
    {
        Icon,
        Text,
        All
    }

    public class XmButton : Button
    {
        private static string DefaultColor = "#FF08979C";
        private static bool IsDark = false;

        #region DependencyProperties

        public static readonly DependencyProperty TypeProperty;
        public static readonly DependencyProperty HoverBackgroundProperty;
        public static readonly DependencyProperty ActiveBackgroundProperty;
        public static readonly DependencyProperty HoverForegroundProperty;
        public static readonly DependencyProperty ActiveForegroundProperty;
        public static readonly DependencyProperty CornerRadiusProperty;

        public XmButtonType Type
        {
            get => (XmButtonType)GetValue(TypeProperty);
            set => SetValue(TypeProperty, value);
        }

        public Brush HoverBackground
        {
            get => (Brush)GetValue(HoverBackgroundProperty);
            set => SetValue(HoverBackgroundProperty, value);
        }

        public Brush ActiveBackground
        {
            get => (Brush)GetValue(ActiveBackgroundProperty);
            set => SetValue(ActiveBackgroundProperty, value);
        }

        public Brush HoverForeground
        {
            get => (Brush)GetValue(HoverForegroundProperty);
            set => SetValue(HoverForegroundProperty, value);
        }

        public Brush ActiveForeground
        {
            get => (Brush)GetValue(ActiveForegroundProperty);
            set => SetValue(ActiveForegroundProperty, value);
        }

        public CornerRadius CornerRadius
        {
            get { return (CornerRadius)GetValue(CornerRadiusProperty); }
            set { SetValue(CornerRadiusProperty, value); }
        }

        #endregion

        static XmButton()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(XmButton), 
                new FrameworkPropertyMetadata(typeof(XmButton)));
            HorizontalContentAlignmentProperty.OverrideMetadata(typeof(XmButton), 
                new FrameworkPropertyMetadata(HorizontalAlignment.Left));

            // 注册依赖属性
            TypeProperty = DependencyProperty.Register(
                nameof(Type), 
                typeof(XmButtonType), 
                typeof(XmButton),
                new PropertyMetadata(XmButtonType.Plain, OnTypeChanged));

            HoverBackgroundProperty = DependencyProperty.Register(
                nameof(HoverBackground), 
                typeof(Brush), 
                typeof(XmButton));

            ActiveBackgroundProperty = DependencyProperty.Register(
                nameof(ActiveBackground), 
                typeof(Brush), 
                typeof(XmButton));

            HoverForegroundProperty = DependencyProperty.Register(
                nameof(HoverForeground), 
                typeof(Brush), 
                typeof(XmButton));

            ActiveForegroundProperty = DependencyProperty.Register(
                nameof(ActiveForeground), 
                typeof(Brush), 
                typeof(XmButton));

            CornerRadiusProperty = DependencyProperty.Register(
                nameof(CornerRadius), 
                typeof(CornerRadius), 
                typeof(XmButton),
                new PropertyMetadata(new CornerRadius(4)));
        }

        private static void OnTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is XmButton button)
            {
                button.UpdateColors();
            }
        }

        public XmButton()
        {
            // 在构造函数中初始化颜色
            UpdateColors();
        }

        private void UpdateColors()
        {
            var primaryColor = string.IsNullOrEmpty(PrimaryColor) ?
                (Color)ColorConverter.ConvertFromString(DefaultColor) :
                (Color)ColorConverter.ConvertFromString(PrimaryColor);

            Background = CreateBackground(Type, primaryColor);
            HoverBackground = CreateHoverBackground(Type, primaryColor);
            ActiveBackground = CreateActiveBackground(Type, primaryColor, EnableGradient);
            Foreground = CreateForeground(Type, primaryColor, TextColor);
            HoverForeground = CreateHoverForeground(Type, primaryColor, TextColor);
            ActiveForeground = CreateActiveForeground(Type, primaryColor, TextColor);
        }

        #region Color Calculation Methods

        private static Brush CreateBackground(XmButtonType type, Color primaryColor)
        {
            switch (type)
            {
                case XmButtonType.Fill:
                    var lighterColor = Kit.AdjustBrightness(primaryColor, 1.2);
                    var gradient = new LinearGradientBrush();
                    gradient.StartPoint = new Point(0, 0);
                    gradient.EndPoint = new Point(1, 0);
                    gradient.GradientStops.Add(new GradientStop(lighterColor, 0.0));
                    gradient.GradientStops.Add(new GradientStop(primaryColor, 1.0));
                    return gradient;
                case XmButtonType.Text:
                case XmButtonType.Plain:
                default:
                    return new SolidColorBrush(Colors.Transparent);
            }
        }

        private static Brush CreateHoverBackground(XmButtonType type, Color primaryColor)
        {
            switch (type)
            {
                case XmButtonType.Fill:
                    var lighterColor = Kit.AdjustBrightness(primaryColor, 1.2);
                    var gradient = new LinearGradientBrush();
                    gradient.StartPoint = new Point(0, 0);
                    gradient.EndPoint = new Point(1, 0);
                    gradient.GradientStops.Add(new GradientStop(primaryColor, 0.0));
                    gradient.GradientStops.Add(new GradientStop(lighterColor, 1.0));
                    return gradient;
                case XmButtonType.Text:
                    return new SolidColorBrush(Colors.Transparent);
                case XmButtonType.Plain:
                default:
                    return new SolidColorBrush(Color.FromArgb(25, primaryColor.R, primaryColor.G, primaryColor.B));
            }
        }

        private static Brush CreateActiveBackground(XmButtonType type, Color primaryColor, bool enableGradient)
        {
            switch (type)
            {
                case XmButtonType.Plain:
                    if (!enableGradient)
                    {
                        return new SolidColorBrush(primaryColor);
                    }
                    var color1 = Kit.AdjustBrightness(primaryColor, 1.2);
                    var gradient1 = new LinearGradientBrush();
                    gradient1.StartPoint = new Point(0, 0);
                    gradient1.EndPoint = new Point(1, 0);
                    gradient1.GradientStops.Add(new GradientStop(color1, 0.0));
                    gradient1.GradientStops.Add(new GradientStop(primaryColor, 1.0));
                    return gradient1;
                case XmButtonType.Fill:
                    if (!enableGradient)
                    {
                        var brighterColor = Kit.AdjustBrightness(primaryColor, 1.3);
                        return new SolidColorBrush(brighterColor);
                    }
                    var color2 = Kit.AdjustBrightness(primaryColor, 1.4);
                    var color3 = Kit.AdjustBrightness(primaryColor, 1.2);
                    var gradient2 = new LinearGradientBrush();
                    gradient2.StartPoint = new Point(0, 0);
                    gradient2.EndPoint = new Point(1, 0);
                    gradient2.GradientStops.Add(new GradientStop(color2, 0.0));
                    gradient2.GradientStops.Add(new GradientStop(color3, 1.0));
                    return gradient2;
                case XmButtonType.Text:
                    return new SolidColorBrush(Colors.Transparent);
                default:
                    return new SolidColorBrush(Colors.Transparent);
            }
        }

        private static Brush CreateForeground(XmButtonType type, Color primaryColor, string textColor)
        {
            switch (type)
            {
                case XmButtonType.Plain:
                case XmButtonType.Text:
                    if (!string.IsNullOrEmpty(textColor))
                    {
                        return new SolidColorBrush((Color)ColorConverter.ConvertFromString(textColor));
                    }
                    return new SolidColorBrush(IsDark?
                        Colors.White : Colors.Black);
                case XmButtonType.Fill:
                    if (!string.IsNullOrEmpty(textColor))
                    {
                        return new SolidColorBrush((Color)ColorConverter.ConvertFromString(textColor));
                    }
                    return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FEFEFEFF"));
                default:
                    return new SolidColorBrush(Colors.Black);
            }
        }

        private static Brush CreateHoverForeground(XmButtonType type, Color primaryColor, string textColor)
        {
            switch (type)
            {
                case XmButtonType.Plain:
                    return new SolidColorBrush(IsDark ? 
                        Colors.White : Colors.Black);
                case XmButtonType.Fill:
                    if (!string.IsNullOrEmpty(textColor))
                    {
                        var baseColor = (Color)ColorConverter.ConvertFromString(textColor);
                        return new SolidColorBrush(Color.FromArgb(
                            baseColor.A,
                            (byte)Math.Min(255, baseColor.R * 1.6),
                            (byte)Math.Min(255, baseColor.G * 1.6),
                            (byte)Math.Min(255, baseColor.B * 1.6)));
                    }
                    return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFFFFFFF"));
                case XmButtonType.Text:
                    return new SolidColorBrush(primaryColor);
                default:
                    return new SolidColorBrush(Colors.Black);
            }
        }

        private static Brush CreateActiveForeground(XmButtonType type, Color primaryColor, string textColor)
        {
            switch (type)
            {
                case XmButtonType.Plain:
                    return new SolidColorBrush(Colors.White);
                case XmButtonType.Fill:
                    if (!string.IsNullOrEmpty(textColor))
                    {
                        var baseColor = (Color)ColorConverter.ConvertFromString(textColor);
                        return new SolidColorBrush(Color.FromArgb(
                            baseColor.A,
                            (byte)Math.Min(255, baseColor.R * 2.4),
                            (byte)Math.Min(255, baseColor.G * 2.4),
                            (byte)Math.Min(255, baseColor.B * 2.4)));
                    }
                    return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFFFFFFF"));
                case XmButtonType.Text:
                    return new SolidColorBrush(primaryColor);
                default:
                    return new SolidColorBrush(Colors.Black);
            }
        }



        #endregion

        #region DependencyProperties

        public string Icon
        {
            get { return (string)GetValue(IconProperty); }
            set { SetValue(IconProperty, value); }
        }

        public static readonly DependencyProperty IconProperty =
            DependencyProperty.Register("Icon", typeof(string), typeof(XmButton), 
                new PropertyMetadata(string.Empty));

        public string ButtonText
        {
            get { return (string)GetValue(ButtonTextProperty); }
            set { SetValue(ButtonTextProperty, value); }
        }

        public static readonly DependencyProperty ButtonTextProperty =
            DependencyProperty.Register("ButtonText", typeof(string), typeof(XmButton), 
                new PropertyMetadata(string.Empty));

        public string PrimaryColor
        {
            get { return (string)GetValue(PrimaryColorProperty); }
            set { SetValue(PrimaryColorProperty, value); }
        }

        public static readonly DependencyProperty PrimaryColorProperty =
            DependencyProperty.Register("PrimaryColor", typeof(string), typeof(XmButton), 
                new PropertyMetadata(null, OnPrimaryColorChanged));

        private static void OnPrimaryColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is XmButton button)
            {
                button.UpdateColors();
            }
        }

        public XmButtonShowMode ShowMode
        {
            get { return (XmButtonShowMode)GetValue(ShowModeProperty); }
            set { SetValue(ShowModeProperty, value); }
        }

        public static readonly DependencyProperty ShowModeProperty =
            DependencyProperty.Register("ShowMode", typeof(XmButtonShowMode), typeof(XmButton), 
                new PropertyMetadata(XmButtonShowMode.All));

        public static readonly DependencyProperty IconSizeProperty =
            DependencyProperty.Register("IconSize", typeof(double), typeof(XmButton), new PropertyMetadata(14.0));

        public double IconSize
        {
            get { return (double)GetValue(IconSizeProperty); } 
            set { SetValue(IconSizeProperty, value); }
        }

        public bool IsActive
        {
            get { return (bool)GetValue(IsActiveProperty); }
            set { SetValue(IsActiveProperty, value); }
        }

        public static readonly DependencyProperty IsActiveProperty =
            DependencyProperty.Register("IsActive", typeof(bool), typeof(XmButton), 
                new PropertyMetadata(false, OnIsActiveChanged));

        private static void OnIsActiveChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is XmButton button)
            {
                // 当 IsActive 改变时，强制更新前景色
                button.CoerceValue(ForegroundProperty);
            }
        }

        public string TextColor
        {
            get { return (string)GetValue(TextColorProperty); }
            set { SetValue(TextColorProperty, value); }
        }

        public static readonly DependencyProperty TextColorProperty =
            DependencyProperty.Register("TextColor", typeof(string), typeof(XmButton), 
                new PropertyMetadata(null, OnTextColorChanged));

        private static void OnTextColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is XmButton button)
            {
                button.UpdateColors();
            }
        }

        public bool EnableGradient
        {
            get { return (bool)GetValue(EnableGradientProperty); }
            set { SetValue(EnableGradientProperty, value); }
        }

        public static readonly DependencyProperty EnableGradientProperty =
            DependencyProperty.Register("EnableGradient", typeof(bool), typeof(XmButton),
                new PropertyMetadata(true, OnEnableGradientChanged));

        private static void OnEnableGradientChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is XmButton button)
            {
                button.UpdateColors();
            }
        }

        #endregion

        /// <summary>
        /// 获取是否显示ToolTip
        /// </summary>
        private bool ShouldShowToolTip => ShowMode == XmButtonShowMode.Icon && !string.IsNullOrEmpty(ButtonText);

        /// <summary>
        /// 重写OnPropertyChanged，用于处理ToolTip显示逻辑
        /// </summary>
        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);
            
            // 当ShowMode或ButtonText变化时，重新评估ToolTip显示
            if (e.Property == ShowModeProperty || e.Property == ButtonTextProperty)
            {
                // 触发模板刷新
                OnApplyTemplate();
            }
        }

        /// <summary>
        /// 重写OnApplyTemplate以应用自定义逻辑
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            
            // 获取ToolTip元素
            if (GetTemplateChild("buttonToolTip") is ToolTip toolTip)
            {
                // 根据条件设置ToolTip可见性
                toolTip.Visibility = ShouldShowToolTip ? Visibility.Visible : Visibility.Collapsed;
            }
        }
    }
} 